package com.trainoo.aspect;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Administrator on 2017/6/5.
 */
@Aspect
@Component
public class HttpAspect {

    private Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    private ObjectMapper mapper = new ObjectMapper();

    /*@Before("execution(public * com.trainoo.controller.GirlController.*(..))")
    public void log(){
        System.out.println("Aop 切面，在方法執行之前就執行");
    }*/

    //如果多个相同的切面，可以这么写
    @Pointcut("execution(public * com.trainoo.controller..*.*(..))")
    public void log(){
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) throws JsonProcessingException {
        ServletRequestAttributes atti = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = atti.getRequest();

        logger.info("===================== 进入切面 ======================");
        logger.info("请求接口：{}", request.getRequestURI());
        logger.info("访问来源IP：{}", request.getRemoteAddr());
        logger.info("请求方法名：{}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        logger.info("请求参数：{}" + mapper.writeValueAsString(joinPoint.getArgs()));
    }

    @After("log()")
    public void doAfter(){
        logger.info("===================== 退出切面 ======================");
    }

    @AfterReturning(returning = "object", pointcut = "log()")
    public void response(Object object) throws JsonProcessingException {
       logger.info("返回值：{}", mapper.writeValueAsString(object));
    }
}
